// pages/marketing/poster/index/index.js
import { queryByTypePage, mmsPosterTypePage, QRCode, centerCount ,getCarNumber} from '../../../../../config/config'
const getURL = require('../../../../../utils/util')   //引入配置接口文件
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    statusBarHeight: app.globalData.statusHeight,//状态栏高度
    curSortId: '', //当前所选分类ID
    userInfo:'',//用户信息
    canvasHeight:500,// canvas高度
    screenWidth:wx.getSystemInfoSync().windowWidth,
    sortData:[], // 海报类型
    listData: [], // 列表数据
    titleHeight: 104, // 顶部高度
    navHeight:50, // 底部主导航高度
    modelPopup:'', // 弹窗类型： sort-pop 分类筛选，share-pop-download 分享下载
    canvasAvatar:'',//分享海报头像
    canvasMainPic:'',//分享海报主图
    canvasQrCode:'',//分享海报二维码
    canvasBottomBg:'',//分享海报底部图片
    detailData: {}, // 当前分享的海报数据
    showSortPop:false,//是否显示筛选
    swiperIndex:0,//轮播索引
    carGoods:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
    that.getFixedHeight()
    that.getmmsPosterTypePage()
    that.getUserInfo()
    that.getCanvasBtImageInfo()
    that.getCarGoodsNumber()
  },
  getCarGoodsNumber() { //查询购物车商品数-
    var that = this;
    app.reqFun.requestJson('POST', getCarNumber, '', (res) => {
      if (res.data.success == 1) {
        that.setData({
          carGoods: res.data.data
        })
      }
    }, true)
  },
  // 获取固定区域的高度
  getFixedHeight(){
    const query = wx.createSelectorQuery()
    query.select('#pagehead').boundingClientRect()
    query.exec((res)=>{
      if (res[0]) {
        this.setData({
          titleHeight:res[0].height || 0
        })
      }
    })
    const nav = wx.createSelectorQuery()
    nav.select('#navBar').boundingClientRect()
    nav.exec((res)=>{
      if (res[0]) {
        this.setData({
        navHeight:res[0].height || 0
        })
      }
    })
  },
  // 选择分类
  selectSort(e) {
    let id = e.currentTarget.dataset.id
    this.setData({
      curSortId: id,
     })
     this.getqueryByTypePage()
  },
  //获取轮播索引
 getSwiperPage:function(e){ 
  let {current, source} = e.detail
  if(source === 'autoplay' || source === 'touch') {
    this.setData({
      swiperIndex: current
    })
  }
 },

  // 获取海报类型
  getmmsPosterTypePage() {
    let that = this
    app.reqFun.requestForm('GET',mmsPosterTypePage + '/promotion','',(res)=>{
      if(res.data && res.data.success==1){
        let records = (res.data &&  res.data.data) || []
        that.setData({
          sortData: records,
          curSortId: records.length?records[0].id:''
        })
        that.getqueryByTypePage()
      }
    }) 
  },
   // 获取海报列表
   getqueryByTypePage() {
    let that = this
    const typeid =this.data.curSortId
    let queryByTypePageUrl = queryByTypePage + '/' + typeid
    app.reqFun.requestForm('GET',queryByTypePageUrl,'',(res)=>{
      if(res.data && res.data.success==1){
        let records = res.data && res.data.data.map(v=>{
          return {...v,...{pic:getURL.getImgUrl(v.pic)}}
        })
        that.setData({
          listData: records,
          swiperIndex:0
        })
      }
    }) 
  },
  // 获取个人头像与昵称
  getUserInfo() {
    const that=this
   app.reqFun.requestJson('GET',centerCount,'',(response)=>{
     if(response.data){
       const res=response.data
       if(res.success === 1 && res.data) {
         let userInfo=res.data.userInfo
         let userIcon = ''
         let loginMsg = wx.getStorageSync('loginMsg')
         if(loginMsg.partner && loginMsg.partnerInfo) {
          userIcon = getURL.getImgUrl(loginMsg.partnerInfo.partnerPhoto)
          userInfo.icon = userIcon
          userInfo.nickname = loginMsg.partnerInfo.partnerNickName
          userInfo.phone = loginMsg.partnerInfo.partnerPhone
         } else {
          userIcon = getURL.getImgUrl(userInfo.icon)
          userInfo.icon = userIcon
         }
         that.setData({
           userInfo
         })
         // 获取当前头像信息，以备保存分享海报时使用
         wx.getImageInfo({             
           src: userIcon,     
           success: function(res) {  
             that.setData({
               canvasAvatar:res.path
             })
           }
         })
       }
     }
   })
 },
  // 跳转到详情页面
  pageJump(e){
    const data=e.currentTarget.dataset.data
    let urltype = data.urlType
    let url =data.url
    let activityPageId = data.activityPageId
    
    if (urltype == 'h5') {
      wx.navigateTo({
        url: '../posterh5/posterh5?h5Url=' + url
      })
    } else if(urltype == 'activityPage') {
      wx.navigateTo({
        url: '../../activityPage/activityPage?id=' + activityPageId,
      })
    } else {
      wx.navigateTo({
        url: url
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  // 展开分类筛选
  openConditonPop(){   
    this.setData({
      modelPopup:'sort-pop'
    })
  },
  //关闭弹窗
  onCloseModel(e){
    this.setData({
      modelPopup:'',
      detailData:{}
    })
  },
  getCaption(obj){
    let arry = obj.split("?")
    console.log('arry[0]', arry[0])
    this.setData({
      pageUrl: arry[0]
    })
    let index = arry[1].lastIndexOf("=")
    let newId  = arry[1].substring(index+1, obj.length)
    return newId
  },
  //打开分享海报弹窗
  openShareModal:function(e){
    let that = this
    app.getLogin((re)=>{
      if(re){
        let item = e.currentTarget.dataset.data
        const userId=wx.getStorageSync('loginMsg').userId
        let parms
        if (item.urlType == 'activityPage') {
          parms={
            page:`packagBuy/pages/marketing/activityPage/activityPage`,
            scene:JSON.stringify({userId:userId,id:item.activityPageId})
          }
        } else if(item.urlType == 'miniPage') {
          if (item.url == '/pages/newIndex/newIndex') {
            parms={
              page:`pages/newIndex/newIndex`,
              scene:JSON.stringify({userId:userId})
            }
          } else {
            let id = that.getCaption(item.url)
            let pageUrl = that.data.pageUrl
            console.log('pageUrl', pageUrl)
            if (pageUrl == '/packageLive/pages/spellBuy/groupActivity/groupActivity') {
              parms={
                page:`packageLive/pages/spellBuy/groupActivity/groupActivity`,
                scene:JSON.stringify({userId:userId,id:id})
              }
            }
            if (pageUrl == '/packageLive/pages/cutPrice/cutPriceActivity/cutPriceActivity') {
              parms={
                page:`packageLive/pages/cutPrice/cutPriceActivity/cutPriceActivity`,
                scene:JSON.stringify({userId:userId,id:id})
              }
            }
            if (pageUrl == '/packageShop/pages/goodsInfo/goodsInfo') {
              parms={
                page:`packageShop/pages/goodsInfo/goodsInfo`,
                scene:JSON.stringify({userId:userId,skuId:id})
              }
            }
            if (pageUrl == '/packagBuy/pages/specialColumn/specialColumn') {
              parms={
                page:`packagBuy/pages/specialColumn/specialColumn`,
                scene:JSON.stringify({userId:userId,id:id})
              }
            }
          }
        } else {
          wx.showToast({
            title: '该海报不可分享',
            icon: 'error'
          })
          return
        }
      
        that.getCavasMainImage(item.pic)
        // 生成分享二维码
        app.reqFun.requestJson('POST',QRCode,parms,(response)=>{
          if(response.data){
            const res=response.data
            if(res.success==1 && res.data){
              that.setData({
                shearImg:`data:image/png;base64,${res.data}`,
                modelPopup:'share-pop-download',
                detailData: item
              })
              that.saveShareCodeToCashImg(`data:image/png;base64,${res.data}`)
            }
          }
        })
      } else {
        if (wx.getUserProfile) {
          app.getUserProfile(function(){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          })
        } else {
          if(!wx.getStorageSync('loginMsg').bindingPhone){
            that.setData({
              getPhoneNumberData:{
                isShowGetPhoneNumber:true
              }
            })
          }
        }
        // that.setData({
        //   isShowGetUserInfo: true
        // })
      }
    })
  },
    //base64图片转本地缓存图片
    saveShareCodeToCashImg(code) {
      const that=this;
      const fs = wx.getFileSystemManager();
      //随机定义路径名称
      var times = new Date().getTime();
      const cashImgPath = wx.env.USER_DATA_PATH + '/' + times + '.png';
      //将base64图片写入
      fs.writeFile({
        filePath: cashImgPath,
        data: code.slice(22),
        encoding: 'base64',
        success: function() { 
          that.setData({
            canvasQrCode:cashImgPath
          })
        }
      });
    },
    // 获取分享主图的图片信息，以备保存海报图片到手机相册时使用
    getCavasMainImage(mainImage){
      const that=this
      wx.getImageInfo({             
        src: getURL.getImgUrl(mainImage),     
        success:function(res) {
          that.setData({
            canvasMainPic:res.path,
            mainPicWidth:res.width,
            mainPicHeight:res.height
          })
        }
      })
    },
     //分享海报
    downloadCanvas:function(e){
      const that=this
      wx.showLoading({
        title: '图片生成中···',
      })
      const contentDetail=that.data.detailData
      const userName=that.data.userInfo.nickname
      const userPhone=that.data.userInfo.phone
      const canvasAvatar=that.data.canvasAvatar
      const canvasMainPic=that.data.canvasMainPic
      const canvasQrCode=that.data.canvasQrCode
      const canvasBottomBg=that.data.canvasBottomBg
      const shareTitle= contentDetail.name
      const shareDesc=contentDetail.description
      const unit = that.data.screenWidth / 375;

      const ctx= wx.createCanvasContext('share-poster');
      // ctx.beginPath() //绘制用户信息区域的背景
      // ctx.setFillStyle('#fff')
      // ctx.fillRect(0, 0, unit * 300, unit * 62)
      // ctx.save()

      const avatorWidth = unit * 42
      const avatorHeight = unit * 42
      const avatarurlX = unit * 10;   //绘制的头像在画布上的位置
      const avatarurlY = unit * 10;   //绘制的头像在画布上的位置

      // ctx.beginPath() //绘制用户头像
      // ctx.arc(avatorWidth / 2 + avatarurlX, avatorHeight / 2 + avatarurlY, avatorWidth / 2, 0, Math.PI * 2, false); // 创建一个圆
      // ctx.clip() // 从原始画布中剪切圆形
      // ctx.drawImage(canvasAvatar,avatarurlX,avatarurlY,avatorWidth,avatorHeight) // 网络图片要通过 getImageInfo / downloadFile 先下载
      // ctx.restore()

      // ctx.beginPath()   //开始绘制用户名称
      // ctx.setFillStyle('#333')
      // ctx.font="bold 14px Arial";
      // ctx.setFontSize(unit * 14);
      // if(userPhone) {
      //   ctx.fillText(userName,unit * 64,unit * 20)
      // } else {
      //   ctx.fillText(userName,unit * 64,unit * 27)
      // }

      // if(userPhone) {
      //   ctx.beginPath()   //开始绘制用户电话
      //   ctx.setFillStyle('#333')
      //   ctx.font="bold 14px Arial";
      //   ctx.setFontSize(unit * 14);
      //   ctx.fillText(userPhone,unit * 64,unit * 38)
      // }
      
      // // ctx.beginPath()  //绘制标签
      // ctx.setFillStyle('#888')
      // ctx.font="12px Arial";
      // ctx.setFontSize(unit * 12);
      // if(userPhone) {
      //   ctx.fillText('邀您参加活动', unit * 64, unit * 55)
      // } else {
      //   ctx.fillText('邀您参加活动', unit * 64, unit * 50)
      // }
     
      

      const mainPicY = unit
      // const mainPicHeight = unit * 148
      const mWidth= that.data.mainPicWidth || 280
      const mHeight= that.data.mainPicHeight || 148
      const mainPicHeight = unit * (280/mWidth * mHeight)
      ctx.beginPath()   //绘制主图
      // ctx.setFillStyle('#fff')
      ctx.fillRect(0, mainPicY, unit * 300, unit * 62)
      ctx.drawImage(canvasMainPic,unit * 1,mainPicY,unit * 280,mainPicHeight)
      ctx.restore()
      
      const wordAreaY= mainPicY + mainPicHeight
      ctx.beginPath()   //开始绘制文字描述部分白色背景图
      ctx.setFillStyle('#fff')
      ctx.fillRect(0, wordAreaY, unit * 300, unit * 140)

      const titleY = wordAreaY + unit * (10 + 14 + 3) // 标题Y轴起始点:10为间距，14 字体高度，3为20的行距减去字体大小14再除以2

      // ctx.beginPath() //绘制用户信息区域的背景
      // ctx.setFillStyle('#fff')
      // ctx.fillRect(0, 0, unit * 300, unit * 62)
      

      ctx.beginPath()   //开始绘制用户名称
      ctx.setFillStyle('#333')
      ctx.font="bold 14px Arial";
      ctx.setFontSize(unit * 14);
      let titleHeight
      if(userPhone) {
      titleHeight = this.drawText(ctx, userName, unit * 64, titleY+7, unit * 280, unit * 20, unit) //处理标题文字换行且绘制标题
      } else {
      titleHeight = this.drawText(ctx, userName, unit * 64, titleY+17, unit * 280, unit * 20, unit) //处理标题文字换行且绘制标题
      }

      if(userPhone) {
        ctx.beginPath()   //开始绘制用户电话
        ctx.setFillStyle('#333')
        ctx.font="bold 14px Arial";
        ctx.setFontSize(unit * 14);
        this.drawText(ctx, userPhone, unit * 64, titleY+27, unit * 280, unit * 20, unit)
      }

      ctx.beginPath()  //绘制标签
      ctx.setFillStyle('#888')
      ctx.font="12px Arial";
      ctx.setFontSize(unit * 12);
      if(userPhone) {
        // ctx.fillText('邀您参加活动', unit * 64, unit * 55)
        this.drawText(ctx, '邀您参加活动', unit * 64, titleY+47, unit * 280, unit * 20, unit)
      } else {
        // ctx.fillText('邀您参加活动', unit * 64, unit * 50)
        this.drawText(ctx, '邀您参加活动', unit * 64, titleY+42, unit * 280, unit * 20, unit)
      }
      // ctx.font="bold "+(unit * 14)+"px 微软雅黑"; // 设置标题字体大小
      // ctx.setFontSize(unit * 14);
      // ctx.setFillStyle('#333') // 设置标题字体颜色
      

      const descY = titleY + titleHeight + unit*10 //描述文字Y轴起点：10 间距，12字体大小，5，行距减去字体大小的一半
      // ctx.font=(unit * 12)+"px 微软雅黑";
      // ctx.setFontSize(unit * 12);
      // ctx.setFillStyle('#333')      
      let descHeight = unit * 10 //字体换行
      // // ctx.restore()
      // if(descHeight< unit * 88){
      //   descHeight = unit * 88 // 文字描述高度最低 88 
      // }

      const codeTopTitle = titleY + titleHeight - (34 + 3) * unit // 二维码Y轴起点(位置烤近标题最后一行,)
      const codeImgHeight = unit * 70
      let  codeImgY = descY + descHeight - (codeImgHeight + 40 * unit) // 二维码低部与描述文字底部对齐
      if(codeTopTitle>codeImgY){
        codeImgY=codeTopTitle
      }

      // ctx.beginPath() //绘制二维码
      // ctx.setFillStyle('#ff00ff')
      // ctx.fillRect(unit * 180,codeImgY,unit * 80,codeImgHeight)
      ctx.drawImage(canvasQrCode,unit * 190,codeImgY,unit * 70,codeImgHeight)

      const codeDescY = codeImgY + codeImgHeight + (10+3) * unit // 二维码提示文字Y轴起点 ：10字体大小，3 为距离二维码的间距
      ctx.font="10px Arial";
      ctx.setFontSize(unit * 10);
      ctx.setFillStyle('#888')
      ctx.fillText('长按/扫描识别',unit * 190, codeDescY)
      // ctx.restore()
      const btBgY = codeImgY + codeImgHeight + (3 * unit)
      // ctx.beginPath() //绘制底部背景
      // ctx.drawImage(canvasBottomBg,0,btBgY,unit * 300,unit * 68)
      // ctx.restore();
      const canvasHeight=btBgY + (unit * 28)
      that.setData({
        canvasHeight
      })
      // console.log('canvasHeight',canvasHeight)
      ctx.save()
      ctx.beginPath() //绘制用户头像
      ctx.arc(avatorWidth / 2 + avatarurlX, avatorHeight / 2 + titleY, avatorWidth / 2, 0, Math.PI * 2, false); // 创建一个圆
      ctx.clip() // 从原始画布中剪切圆形
      ctx.drawImage(canvasAvatar,avatarurlX,titleY,avatorWidth,avatorHeight)
      ctx.restore()
      setTimeout(()=>{
        ctx.draw(true,()=>{ 
          wx.canvasToTempFilePath({   //canvas生成图片
            x: 0,
            y: mainPicY,
            width: unit * 280,
            height: canvasHeight,
            canvasId: 'share-poster',
            fileType: 'png',
            success(res) {
              wx.saveImageToPhotosAlbum({     //保存图片到相册
                filePath:res.tempFilePath,
                success:function(e){
                  wx.hideLoading({})
                  wx.showToast({
                    title: '保存图片成功',
                    duration:3000
                  })
                  that.setData({
                    modelPopup:''
                  })
                },
                fail:function(e){
                  wx.hideLoading({})
                  wx.showModal({
                    title: '保存失败',
                    content: '保存图片失败,请点击右上角按钮-设置-开启授权',
                    showCancel:false,
                  })
                }
              })   
            },fail(res){
              console.log(res)
            }
          })
        })
      },1000)

    },
    // 获取分享图片底部背景图信息，以备保存分享海报时使用
    getCanvasBtImageInfo(){
      const that=this
      wx.getImageInfo({             
        src: 'https://gcenterimg.quanyou.com.cn/img_source/u_found_share_bottom.png',     
        success: function(res) { 
          that.setData({
            canvasBottomBg:res.path
          })
        }
      })
    },
    /*
  * cavas 文字换行
  * @params {String} ctx canvas组件的绘图上下文
  * @params {String} str 文字字符串内容
  * @params {Number} leftWidth 距离x轴距离
  * @params {Number} initHeight 文字Y轴的起始点
  * @params {Number} canvasWidth 文字画布区域的宽度
  * @params {Number} lineHeight 行高
  * @params {Number} line 行数
  */
 drawText(ctx, str, leftWidth, initHeight, canvasWidth, lineHeight,unit) {        
  let lineWidth = 0;     // 行宽
  let lastSubStrIndex = 0; // 每次开始截取的字符串的索引
  let titleHeight = lineHeight // 文字区域高度
  for (let i = 0; i < str.length; i++) { 
    lineWidth += ctx.measureText(str[i]).width + 1 * unit; //获取一个字符的宽度，加1px空格        
    if (lineWidth > canvasWidth) {                
      ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分文字           
      initHeight += lineHeight; //lineHeight行高          
      lineWidth = 0;                
      lastSubStrIndex = i;                
      titleHeight += lineHeight 
    }            
    if (i == str.length - 1) { //绘制剩余部分                
      ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);            
    }        
  }
  // 标题border-bottom 线距顶部距离        
  // titleHeight = titleHeight + 10 * unit;     
  return titleHeight    
},
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }

  //登录-注册
  bindGetUserInfo: function (e) {
    app.getUserInfo()
    this.setData({
      showSetting: false,
      isShowGetUserInfo: false
    })
  },
  //登录弹窗关闭回调
  onCloseShowGetUserInfo() {
    this.setData({
      showSetting: false,
      isShowGetUserInfo: false
    })
  },
   // 返回
   goreBack(e) {
    wx.navigateBack({
      delta: 1,
    })
  },
})
